#include <NewSoftSerial.h>
#include <uMMC.h>

NewSoftSerial ummc_s(4, 5);

static int8_t availableummc(void);
static int peekummc(void);
static int readfromummc(void);
static void printtoummc(char c);

uMMC ummc1(&availableummc, &peekummc, &readfromummc, &printtoummc);

static void printtoummc(uint8_t c)
{
  ummc_s.print((uint8_t) c);
}

static int readfromummc(void)
{
  return ummc_s.read();
}

static int8_t availableummc(void)
{
  return ummc_s.available();
}

static int peekummc(void)
{
  return ummc_s.peek();
}

void setup()
{
  pinMode(13, OUTPUT);

  Serial.begin(9600);

  ummc_s.begin(9600);
  
  randomSeed(analogRead(0));
}

void loop()
{
  int8_t resp, filehandle;
  char linebuf[60];

  Serial.println("Initializing uMMC");

  // prepares the communications with the uMMC and closes all open files (if any)
  ummc1.sync();
  
  Serial.print("uMMC Version: ");
  Serial.println(ummc1.version());

  // open a file

  Serial.print("Opening file for append: ");

  filehandle = ummc1.open("/filetest1.txt", uMMC::OPEN_APPEND);

  if(filehandle > 0)
  {
    Serial.print("handle ");
    Serial.println(filehandle);

    // append some data

    ummc1.writeln_prep(filehandle);
    // you can use any of the standard print methods to send data to the file.
    ummc1.print("You'll see this many times in this file. RAND: ");
    ummc1.print(random(10000));
    ummc1.writeln_finish();

    ummc1.close(filehandle);

    // now let's read the file
    filehandle = ummc1.open("/filetest1.txt", uMMC::OPEN_READ);
 
    Serial.print("Opening file for read: ");

    if(filehandle > 0)
    {
      Serial.print("handle ");
      Serial.println(filehandle);
 
      // this reads 60 characters at a time (if available, per line)
      while(ummc1.readln(filehandle, 60, linebuf) > 0)
      {
        Serial.println(linebuf);
      
        delay(200);  // pause 200 milliseconds between lines
      }
      
      ummc1.close(filehandle);
    }
    else
    {
      Serial.print("ERROR: ");
      Serial.println(ummc1.LastErrorCode, HEX);
    }
  }
  else
  {
    Serial.print("ERROR: ");
    Serial.println(ummc1.LastErrorCode, HEX);
  }

  while(1);  // just loop infinitely here at the end, wait for reset

}
